package com.bbznb.service.serviceImpl;

import io.minio.GetPresignedObjectUrlArgs;
import io.minio.MinioClient;
import io.minio.PutObjectArgs;
import io.minio.errors.InsufficientDataException;
import io.minio.errors.InternalException;
import io.minio.errors.InvalidResponseException;
import io.minio.errors.XmlParserException;
import io.minio.http.Method;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.stereotype.Service;
import org.springframework.web.ErrorResponseException;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.rmi.ServerException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.text.DateFormat;
import java.text.Format;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.Random;
import java.util.UUID;

@Service
public class MinIOService {

    private MinioClient minioClient;
    private String bucketName;

    public void SetMinIOService(MinioClient minioClient, String bucketName) {
        this.minioClient = minioClient;
        this.bucketName = bucketName;
    }

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    public String uploadImage(MultipartFile file) throws IOException, ServerException, InsufficientDataException,
            ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, XmlParserException,
            InternalException, io.minio.errors.ServerException, io.minio.errors.ErrorResponseException,
            InvalidResponseException, InternalException {

        // 生成短文件名（格式：yyMMdd-随机数）
        DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("yyMMdd");
        String datePart = LocalDate.now().format(dateFormat);
        String randomId = generateRandomId(3); // 生成6位随机字符
        String objectName = datePart + "-" + randomId;

        // 上传文件到MinIO
        minioClient.putObject(PutObjectArgs.builder()
                .bucket(bucketName)
                .object(objectName)
                .contentType(file.getContentType())
                .stream(file.getInputStream(), file.getSize(), -1)
                .build());

        // 生成预签名URL（有效期缩短为1天以减少参数长度）
        return minioClient.getPresignedObjectUrl(GetPresignedObjectUrlArgs.builder()
                .method(Method.GET)
                .bucket(bucketName)
                .object(objectName)
                .expiry(1, java.util.concurrent.TimeUnit.DAYS) // 1天有效期
                .build());
    }

    // 生成指定长度的随机字符串
    private String generateRandomId(int length) {
        String chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
        StringBuilder sb = new StringBuilder();
        Random random = new Random();

        for (int i = 0; i < length; i++) {
            sb.append(chars.charAt(random.nextInt(chars.length())));
        }

        return sb.toString();
    }
}